package client.printing;

import client.common.dto.ItemReportDTO;
import client.common.result.Result;
import remote.service.ExcelExportService;
import remote.service.MaterialService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 仓库账单查询与导出窗口
 */
public class QueryWarehouseLedgerForm extends JFrame {
    
    private JComboBox<String> yearComboBox;
    private JTextField materialIdField; // 物料ID输入框
    private JButton queryButton;
    private JButton exportButton;
    private JTable ledgerTable;
    private LedgerTableModel ledgerTableModel;
    
    private MaterialService ledgerService = new MaterialService() {
    };
    private ExcelExportService excelExportService = new ExcelExportService() {
    };
    
    public QueryWarehouseLedgerForm() {
        setTitle("仓库账单查询与导出");
        setSize(1000, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中
        
        initUI();
    }
    
    /**
     * 启动程序入口
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            QueryWarehouseLedgerForm form = new QueryWarehouseLedgerForm();
            form.setVisible(true);
        });
    }
    
    /**
     * 初始化界面组件
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 上部查询面板
        JPanel queryPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        
        // 年份输入
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        queryPanel.add(new JLabel("年份:"), gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        yearComboBox = new JComboBox<>(); // 确保使用一致的变量名
        for (int year = 2024; year <= 2030; year++) { // 从2024到2030年
            yearComboBox.addItem(String.valueOf(year));
        }
        queryPanel.add(yearComboBox, gbc);
        
        // 物料ID输入
        gbc.gridx = 2;
        gbc.anchor = GridBagConstraints.EAST;
        queryPanel.add(new JLabel("物料ID:"), gbc);
        
        gbc.gridx = 3;
        gbc.anchor = GridBagConstraints.WEST;
        materialIdField = new JTextField(10);
        queryPanel.add(materialIdField, gbc);
        
        // 查询按钮
        gbc.gridx = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        queryButton = new JButton("查询");
        queryPanel.add(queryButton, gbc);
        
        // 导出按钮
        gbc.gridx = 5;
        exportButton = new JButton("导出到Excel");
        queryPanel.add(exportButton, gbc);
        
        mainPanel.add(queryPanel, BorderLayout.NORTH);
        
        // 仓库账单表格
        ledgerTableModel = new LedgerTableModel();
        ledgerTable = new JTable(ledgerTableModel);
        ledgerTable.setFillsViewportHeight(true);
        JScrollPane tableScrollPane = new JScrollPane(ledgerTable);
        mainPanel.add(tableScrollPane, BorderLayout.CENTER);
        
        add(mainPanel);
        
        // 按钮事件
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryWarehouseLedger();
            }
        });
        
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportWarehouseLedger();
            }
        });
    }
    
    /**
     * 查询仓库账单
     */
    private void queryWarehouseLedger() {
        String year = (String) yearComboBox.getSelectedItem(); // 获取选中的年份
        String materialId = materialIdField.getText().trim();
        
        if (year.isEmpty() || materialId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "年份和物料ID不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (!materialId.matches("\\d+")) {
            JOptionPane.showMessageDialog(this, "请输入有效的物料ID。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 使用SwingWorker在后台线程中查询仓库账单
        SwingWorker<Result<List<ItemReportDTO>>, Void> worker = new SwingWorker<Result<List<ItemReportDTO>>, Void>() {
            @Override
            protected Result<List<ItemReportDTO>> doInBackground() throws Exception {
                Long materialIdValue = Long.valueOf(materialId);
                return ledgerService.getReportByMaterialIdAndYear(materialIdValue, year);
            }
            
            @Override
            protected void done() {
                try {
                    Result<List<ItemReportDTO>> result = get();
                    if (result.getCode() == 200) {
                        List<ItemReportDTO> ledgers = result.getData();
                        ledgerTableModel.setLedgers(ledgers);
                        JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "查询成功，共 " + ledgers.size() + " 条记录。", "成功", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "查询失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "查询异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 导出仓库账单到Excel
     */
    private void exportWarehouseLedger() {
        String year = (String) yearComboBox.getSelectedItem(); // 获取选中的年份
        String materialId = materialIdField.getText().trim(); // 获取物料ID
        
        if (year.isEmpty()) {
            JOptionPane.showMessageDialog(this, "年份不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (materialId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "物料ID不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (!materialId.matches("\\d+")) {
            JOptionPane.showMessageDialog(this, "请输入有效的物料ID。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 选择保存路径
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存Excel文件");
        int userSelection = fileChooser.showSaveDialog(this);
        if (userSelection != JFileChooser.APPROVE_OPTION) {
            return;
        }
        
        final String savePath = fileChooser.getSelectedFile().getAbsolutePath();
        String correctedSavePath;
        
        // 检查文件扩展名，并确保为 .xlsx
        if (!savePath.toLowerCase().endsWith(".xlsx")) {
            correctedSavePath = savePath + ".xlsx"; // 添加扩展名
        } else {
            correctedSavePath = savePath; // 保持原路径
        }
        
        // 修改为传入年份和物料ID
        exportToExcel(year, Long.valueOf(materialId), correctedSavePath);
    }
    
    /**
     * 辅助方法：执行导出操作
     */
    private void exportToExcel(String year, Long materialId, final String savePath) {
        // 使用SwingWorker在后台线程中导出仓库账单
        SwingWorker<Result<String>, Void> worker = new SwingWorker<Result<String>, Void>() {
            @Override
            protected Result<String> doInBackground() throws Exception {
                return excelExportService.exportBillToExcel(year, materialId, savePath); // 修改为传入年份和物料ID
            }
            
            @Override
            protected void done() {
                try {
                    Result<String> result = get();
                    if (result.getCode() == 200) {
                        JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "账单导出成功！保存路径: " + savePath, "成功", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "账单导出失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(QueryWarehouseLedgerForm.this, "导出异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 仓库账单表格模型
     */
    // 仓库账单表格模型
    class LedgerTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"物料ID", "物料名称", "物料规格", "物料单位", "提交时间", "总入库", "总出库"};
        private List<ItemReportDTO> ledgers;
        
        public void setLedgers(List<ItemReportDTO> ledgers) {
            this.ledgers = ledgers;
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount() {
            return ledgers == null ? 0 : ledgers.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (ledgers == null || rowIndex >= ledgers.size()) {
                return null;
            }
            ItemReportDTO ledger = ledgers.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return ledger.getMaterialId();
                case 1:
                    return ledger.getMaterialName();
                case 2:
                    return ledger.getMaterialSpecification();
                case 3:
                    return ledger.getMaterialUnit();
                case 4:
                    return formatDate(ledger.getSubmitTime()); // 格式化日期
                case 5:
                    return ledger.getTotalIn();
                case 6:
                    return ledger.getTotalOut();
                default:
                    return null;
            }
        }
        
        /**
         * 格式化日期为字符串
         *
         * @param date 日期对象
         * @return 格式化后的日期字符串
         */
        private String formatDate(Date date) {
            if (date != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据需要调整格式
                return sdf.format(date);
            }
            return "";
        }
    }
}
